#include "head.h"

int transFile(int new_fd)
{
    //先发文件名、再发文件内容
    train_t t;
    t.size=strlen("file1");
    strcpy(t.buf,"file1");
    send(new_fd,&t,4+t.size,0);
    //发送文件内容
    int fd=open("file1",O_RDONLY);
    ERROR_CHECK(fd,-1,"open");

    //发送文件大小给客户端、用于进度打印
    struct stat file_buf;
    fstat(fd,&file_buf);
    t.size=sizeof(file_buf.st_size);
    memcpy(t.buf,&file_buf.st_size,sizeof(file_buf.st_size));
    send(new_fd,&t,4+t.size,0);

    //边读边发
    int ret;
    while(t.size=(read(fd,t.buf,sizeof(t.buf))))
    {
        ret=send(new_fd,&t,4+t.size,0);
        if(-1==ret)
        {
            goto end;//客户端在接收过程中断开了、退出
        }        
    }
    //文件内容发送结束、通知对方
    t.size=0;
    send(new_fd,&t,4+t.size,0);
end:
    close(fd);
    return 0;
}

//循环接收
int recvn(int new_fd,void *pStart,int len)
{
    int total=0,ret;
    char *p=(char *)pStart;
    while(total<len)
    {
        ret=recv(new_fd,p+total,len-total,0);
        ERROR_CHECK(ret,-1,"recv");
        if(0==ret)
        {
            return -1;
        }
        total+=ret;
    }
    return 0;
}


//接收文件
int recvFile(int new_fd)
{
    int recvLen;
    char buf[1000];
    //接收文件名
    recvn(new_fd,&recvLen,4);
    recvn(new_fd,buf,recvLen);
#ifdef DEBUG
    printf("(file name) buf=%s\n",buf);
#endif
    int fd=open(buf,O_WRONLY|O_CREAT,0666);
    ERROR_CHECK(fd,-1,"open");
    //接收文件内瓤
    while(1)
    {
        recvn(new_fd,&recvLen,4);
        if(recvLen>0)
        {
            recvn(new_fd,buf,recvLen);
            write(fd,buf,recvLen);            
        }else{
            break;
        }
    }
    close(fd);
    return 0;
}